const multer = require('multer')
const path = require("path");
const fs = require("fs");
const dirPath = path.resolve(__dirname, '../static/images/')


if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
}


const handleImage = async (req, res) => {
    try {
        // console.log(req.file)
        return res.status(200).send({
            code: '200',
            message: '图片上传成功',
            data: req.file.filename
        })
    } catch (e) {
        console.log('图片上传', e)
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
}

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, dirPath); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
    },
    filename: function(req, file, cb) { // 在这里设定文件名
        cb(null, Date.now() + '-' + file.originalname); // file.originalname是将文件名设置为上传时的文件名，file中携带的
    }
})

exports.AvatorUpload = multer({storage}).single('file')

exports.handleImage = handleImage

// 删除文件
exports.handleDelImg = async (req, res) => {
    try {
        const { url } = req.body
        fs.unlinkSync(path.resolve(dirPath, url))
        return res.status(200).send({
            code: '200',
            message: '图片删除成功',
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
}